import 'package:flutter/material.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:qgchat/common/class/videoCall/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/chatModel.dart';
import 'package:qgchat/states/states_model/user.dart';

class SocketState with ChangeNotifier {
  // ##########  视频通话  ##############

  /// 当前用户是否通话中
  bool onTheCall = false;

  /// 切换通话状态
  toggleCallState(bool state) {
    onTheCall = state;
    notifyListeners();
  }

  // ##########  私聊列表  ##############

  /// 全局私聊列表
  List<ChatModel> chatList = [];

  /// 销毁所有全局量
  disposeAll() {
    chatList = List<ChatModel>();
    notifyListeners();
  }

  /// 初始化私聊列表
  initChatList(List<ChatModel> val) {
    chatList = val;
    notifyListeners();
  }

  /// 初始化私聊详情
  initChatInfo(String token, ChatModel chat) {
    int i = chatList.indexWhere((item) => item.token == token);
    if (i != -1) {
      chatList[i] = chat;
      readMessage(token);
    }
    notifyListeners();
  }

  /// 新增私聊内容(已有私聊用户就新增内容，没有则新增用户)
  addMessage(String token, {String userName, String userHead, Msglist msg, bool iSay = false}) {
    int i = chatList.indexWhere((item) => item.token == token);
    if (i != -1) {
      if (msg != null) {
        chatList[i].msglist.add(msg);
        chatList[i].readCount =
            chatList[i].msglist.where((item) => item.isread == 0).length;
        Global.db.insert(msg);
      }
    } else {
      if (msg != null) {
        chatList.insert(
          0,
          ChatModel(
            token: token,
            userName: userName,
            userHead: userHead,
            readCount: iSay ? 0 : 1,
            msglist: [msg],
          ),
        );
        Global.db.insert(msg);
      }
    }
    notifyListeners();
  }

  /// 找出第一个私聊用户
  queryFirstUser(String token) {
    return chatList.firstWhere((item) => item.token == token);
  }

  /// 跳转到私聊页面
  goChatPage(
    context, {
    int id,
    String token,
    String name,
    String head,
  }) {
    addMessage(
      token,
      userName: name,
      userHead: head,
    );
    VideoCall.checkUserStatusAndGoChatPage(context, token);
  }

  /// 发送消息
  sendMessage(String token, String text, String userName, String userHead) {
    UserState userState = (state(Global.context, 'user') as UserState);

    Msglist msglist = Msglist(
      token: token,
      userToken: userState.info.memberToken,
      message: text,
      type: 0,
      userName: userName,
      userHead: userHead,
      isread: 1,
      createtime: (DateTime.now().millisecondsSinceEpoch / 1000).floor(),
    );

    addMessage(
      token,
      userName: userName,
      userHead: userHead,
      msg: msglist,
      iSay: true,
    );

    Global.ws.sendMessage(token, text);
  }

  /// 已读私聊主播
  readMessage(String token) {
    int i = chatList.indexWhere((item) => item.token == token);
    if (i != -1) {
      chatList[i].readCount = 0;
      chatList[i].msglist.forEach((Msglist item) {
        item.isread = 1;
      });
      Global.db.updateDialogue(token);
    }

    // 设置app红点
    int count = chatList.fold(0, (preValue,item) {
      return preValue + item.readCount;
    });
    if (count > 0) {
      FlutterAppBadger.updateBadgeCount(count);
    } else {
      FlutterAppBadger.removeBadge();
    }

    notifyListeners();
  }

  /// 删除私聊主播
  delMessage(String token) {
    chatList.removeWhere((item) => item.token == token);
    Global.db.deleteDialogue(token);
    notifyListeners();
  }
}
